#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#
# Spectral/hp Element Methods for CFD
# George Em Karniadakis, Spencer J. Sherwin

import numpy as np


def _jacobiP(n, a, b, x):
    ''' values the n-th order jacobi polynomial with parameters
      a and b at the point x.
  '''

    assert 0 <= n and -1. <= a and -1. <= b and abs(x) <= 1.

    if 0 == n:
        return np.array([1, 0, 0], 'float')

    ab = a + b
    y = x * (ab + 2.) / 2. + (a - b) / 2.
    dy = (ab + 2.) / 2.
    d2y = 0
    if 1 == n:
        return np.array([y, dy, d2y], 'float')

    (yp, dyp, d2yp) = (1.0, 0, 0)
    for di in np.linspace(2, n, n - 1, endpoint=True):
        c0 = di * 2. + ab
        c1 = di * 2. * (di + ab) * (c0 - 2.)
        c2 = (c0 - 1.) * (c0 - 2.) * c0
        c3 = (c0 - 1.) * (a - b) * ab
        c4 = (di + a - 1.) * 2. * c0 * (di + b - 1.)

        ym = y
        y = ((c2 * x + c3) * y - c4 * yp) / c1
        yp = ym
        dym = dy
        dy = ((c2 * x + c3) * dy - c4 * dyp + c2 * yp) / c1
        dyp = dym
        d2ym = d2y
        d2y = ((c2 * x + c3) * d2y - c4 * d2yp + c2 * 2. * dyp) / c1
        d2yp = d2ym
    return np.array([y, dy, d2y], 'float')


